package cn.hwadee.muying.service;

import cn.hwadee.muying.commons.base.BaseService;
import cn.hwadee.muying.commons.constant.ConstantRole;
import cn.hwadee.muying.entity.Permission;
import cn.hwadee.muying.entity.Role;
import cn.hwadee.muying.entity.User;
import cn.hwadee.muying.mapper.PermissionMapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Tony
 * @since 2018-04-17
 */
@Service
public class PermissionService extends BaseService<PermissionMapper, Permission> {

    @Autowired
    private PermissionMapper permMapper;

    @Autowired
    private RoleService roleService;

    public List<Permission> list() throws Exception{
        EntityWrapper<Permission> ew = new EntityWrapper<>();
        ew.eq(Permission.VALID,true);
        return super.selectList(ew);
    }

    /**
     * 获取用户的菜单
     * @param currentUser
     * @return
     */
    public List<Permission> menu(User currentUser) {

        String cPerm = "";

        // 根据角色查询权限
        Long roleId = currentUser.getRid();
        if(roleId != null && roleId > 0){
            Role role = roleService.selectById(roleId);
            if(role != null)
                cPerm = role.getPerms();
        }

        if(!currentUser.getRid().equals(ConstantRole.ROLE_SUPER) && StringUtils.isEmpty(cPerm)){
            return new ArrayList<>();
        }

        //获取用户角色对应的菜单
        EntityWrapper<Permission> ew = new EntityWrapper<>();
        if(currentUser.getRid().equals(ConstantRole.ROLE_SUPER)){
            //超级管理员获得所有菜单
            ew = new EntityWrapper<>();
            ew.eq(Permission.VALID, true).eq("`display`", "1").orderBy("pid asc");
        }else {
            ew = new EntityWrapper<>();
            ew.eq(Permission.VALID, true).eq("`display`", "1").in(Permission.ID, cPerm.toString()).orderBy("pid asc");
        }

        List<Permission> userPermList = permMapper.selectList(ew);//注意：使用了Mybatis的缓存，此时得到数据是缓存数据（即已处理过的）！

        Map<Long, Permission> permMap = new HashMap<>();
        for (Permission perm : userPermList) {
            perm.setSubPerms(null);//清除缓存
            permMap.put(perm.getId(), perm);
        }
        List<Permission> perms = new ArrayList<>();

        for (Permission perm : userPermList) {
            if(perm.getPid() != null && perm.getPid() > 0){
                Permission parent = permMap.get(perm.getPid());
                if(parent.getSubPerms() == null){
                    parent.setSubPerms(new ArrayList<>());
                }
                parent.getSubPerms().add(perm);
            }else {
                perms.add(perm);
            }

        }

        return perms;

    }

    public void insertPerm(Permission perm) throws Exception{
        super.insert(perm);
        Role merchantAdmin = roleService.selectById(ConstantRole.ROLE_ORGANIZATION_ADMIN);
        merchantAdmin.setPerms(merchantAdmin.getPerms()+","+perm.getId());
        roleService.updateById(merchantAdmin);
    }

    /**
     * 删除菜单及其子菜单
     * @param id
     * @return
     * @throws Exception
     */
    public Boolean deletePerm(Long id) throws Exception{
        log.info("===删除 id 为[" + id + "]的菜单及其下级菜单===");

        List<Permission> subperms = this.selectSubperms(id);
        for(Permission perm:subperms){
            if(this.selectSubperms(perm.getId()).size() == 0){
                super.deleteById(perm.getId());
            }else {
                deletePerm(perm.getId());
            }
        }
        return super.deleteById(id);
    }

    /**
     * 查询对应 pid 的子菜单
     * @param pid
     * @return
     * @throws Exception
     */
    public List<Permission> selectSubperms(Long pid) throws Exception{
        log.info("===根据 pid [" + pid + "]获得其对应区域===");

        return permMapper.selectSubperms(pid);
    }


}
